package com.ruoyi.business.controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.business.domain.BusDevicePressure;
import com.ruoyi.business.service.IBusDevicePressureService;
import com.ruoyi.common.annotation.Anonymous;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.BusMaintenance;
import com.ruoyi.business.service.IBusMaintenanceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 维保任务Controller
 * 
 * @author wf
 * @date 2024-07-18
 */
@RestController
@RequestMapping("/business/maintenance")
public class BusMaintenanceController extends BaseController
{
    @Autowired
    private IBusMaintenanceService busMaintenanceService;

    @Autowired
    private IBusDevicePressureService busDevicePressureService;

    @Value("${export.max:10000}")
    private Integer max;

    /**
     * 查询维保任务列表
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusMaintenance busMaintenance)
    {
        startPage();
        List<BusMaintenance> list = busMaintenanceService.selectBusMaintenanceList(busMaintenance);
        return getDataTable(list);
    }

    /**
     * 导出维保任务列表
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:export')")
    @Log(title = "维保任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusMaintenance busMaintenance)
    {
        List<BusMaintenance> list = busMaintenanceService.selectBusMaintenanceList(busMaintenance);
        if (list.size() > max) {
            throw new ServiceException("导出失败！,每次最多导出 " + max + "条");
        }
        ExcelUtil<BusMaintenance> util = new ExcelUtil<BusMaintenance>(BusMaintenance.class);
        util.exportExcel(response, list, "维保任务数据");
    }

    /**
     * 获取维保任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(busMaintenanceService.selectBusMaintenanceById(id));
    }

    /**
     * 新增维保任务
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:add')")
    @Log(title = "维保任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusMaintenance busMaintenance)
    {
        // 生成 维保的集合。
        List<BusMaintenance> busMaintenanceList = new ArrayList<>();
        LocalDate someDate = LocalDate.now();
        int year = someDate.getYear();
        int month = someDate.getMonthValue();
        int day = someDate.getDayOfMonth();

// 将年月日组合成一个整数，例如：20230723
        int dateAsInt = Integer.parseInt(year + String.format("%02d", month) + String.format("%02d", day));

        int num = 99;
        if (busMaintenance.getStreetId() == null  || busMaintenance.getNeighborhoodId() == null ||busMaintenance.getDeviceClassification() == null || busMaintenance.getDeviceType() == null ) {
            // 添加所有设备 -- 维保任务   添加多条数据

            // 查询所有设备信息（调压设施），依次添加数据
            List<BusDevicePressure> busDevicePressures =    busDevicePressureService.selectBusDevicePressureList(null);
            //  可以修改查询语句，减少sql执行时间
//            System.out.println("结果：");
//            busDevicePressures.forEach(System.out::println);
//             每条查询出来的数据，封装成一个对象，添加
            for (BusDevicePressure busDevicePressure: busDevicePressures
                 ) {
                BusMaintenance busMaintenance1 = new BusMaintenance();
                // 任务编号         Date 上改的 date+id
                int  num1 = ++num ;

                busMaintenance1.setTaskCode("WB" +dateAsInt+"00000" +num1);
                //  设备编号
                busMaintenance1.setDeviceCode(busDevicePressure.getDeviceCode());
                // 设备类型
                busMaintenance1.setDeviceType(busDevicePressure.getDeviceType());
                //  设施类型
//                busMaintenance1.setDeviceClassification();
                // 街道id
                busMaintenance1.setStreetId(busDevicePressure.getStreetId());
                // 小区id
                busMaintenance1.setNeighborhoodId(busDevicePressure.getNeighborhoodId());

                busMaintenanceList.add(busMaintenance1);
            }
            // 调用service ，完成添加。

             return  toAjax(busMaintenanceService.insertAllBusMaintenance(busMaintenanceList));
        }else {
            return toAjax(busMaintenanceService.insertBusMaintenance(busMaintenance));

        }
//        System.out.println("获取数据：" + busMaintenance.toString());
    }

    /**
     * 修改维保任务
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:edit')")
    @Log(title = "维保任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusMaintenance busMaintenance)
    {
        return toAjax(busMaintenanceService.updateBusMaintenance(busMaintenance));
    }

    /**
     * 删除维保任务
     */
    @PreAuthorize("@ss.hasPermi('business:maintenance:remove')")
    @Log(title = "维保任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(busMaintenanceService.deleteBusMaintenanceByIds(ids));
    }

    /**
     * 获取维保任务总数和已完成维保任务的数量
     *
     * @return {@link AjaxResult }@author admin
     * @date 2024/10/16
     */
    @Anonymous
    @GetMapping("/count")
    public AjaxResult getMaintenanceAndCompleted(){
        return success(busMaintenanceService.getMaintenanceAndCompleted());
    }
}
